<?php
//@app_header;
		
class ajax  {
	
	//if you experience a file not found error, 
	//enter a relateive path to the base/parent directory where the controllers are.
	CONST CONTROLLERS_DIR = "controllers";
	
	function ajax($controller)
	{
		$ajax = ajax();
		$dir = $ajax->get('cjax_dir');

		$getcwd = getcwd();
		
		$params = array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z');
		
		$args = array();
		$arg_count = count(array_keys($_REQUEST)) - 3;
		foreach($params as $k => $v) {
			if(isset($_REQUEST[$v])) {
				if(is_array($_REQUEST[$v])) {
					$args[$v] = array_map('urldecode', $_REQUEST[$v]);
				} else {
					$args[$v] = urldecode($_REQUEST[$v]);
				}
			} else {
				$args[$v] = null;
			}
			if($k >= $arg_count) {
				break;
			}
		}
		
		$controller_dir = self::CONTROLLERS_DIR;
		if(defined('AJAX_CD')) {
			$controller_dir = AJAX_CD;
		} else if(isset($_COOKIE['AJAX_CD']) && $_COOKIE['AJAX_CD']) {
			$controller_dir = $_COOKIE['AJAX_CD'];
		}
		
		$files = array();
		$files[] = "{$dir}/{$controller_dir}/{$controller}.php";
		$files[] = "{$ajax->controller_dir}/{$controller_dir}/{$controller}.php";
		$files[] = dirname(__file__)."/{$controller_dir}/{$controller}.php";
		$files[] = "{$controller_dir}/{$controller}.php";
		
		do {
			if(file_exists($file = $files[key($files)])) {
				break;
			}
		} while( next($files) );
		
		
		if (!is_file($file)) {
			die("Controller File: $file not found");
		}

		require_once $file;
		$class = 'controller_'.$controller;
		if(!class_exists($class)) {
			$class = $controller;
			if(!class_exists($class)) {
				die("Controller class \"{$class}\" not found");
			}
		}
	
		$function = (isset($_REQUEST['function'])? $_REQUEST['function']: null);
		
		$obj = new $class;
		
		if(!method_exists($obj,$function)) {
			if(method_exists($obj,'index')) {
				$function = 'index';
			} else {
				$err = "Controller method/function \"$class::$function()\" not found";
				$ajax->error($err);
				die($err);
			}
		}

		unset($_GET['controller']);
		unset($_GET['function']);
		
		$response = call_user_func_array(array($obj, $function), $args);
		
		if(defined('CJAX_RESPONSE')
		|| defined('AJAX_RESPONSE')
		|| isset($_REQUEST['dataType'])
		|| (is_array($response) && !empty($response))
		|| (is_object($response) && !empty($response)))
		{
			if(!isset($_REQUEST['dataType'])) {
				$_REQUEST['dataType'] = 'string';
			}
			switch($_REQUEST['dataType']) {
				case 'json':
					$response = json_encode($response);
					break;
				default:
				if(is_array($response) || is_object($response)) {
					$response = json_encode($response);
				}
			}
			print $response;
		}
	}
}
define('AJAX_CONTROLLER',1);
require_once (dirname(__file__)).'/cjax/cjax.php';
$ajax = CJAX::getInstance();
$controller = $ajax->get('controller');
if($controller) {
	new ajax($controller);
}